package com.wwb.collect.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.collect.api.RemoteCollectCommonService;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.CommonUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.ImageMergeUtils;
import com.ruoyi.common.core.utils.ListUtils;
import com.ruoyi.common.core.utils.bean.BeanCopyUtils;
import com.ruoyi.common.core.utils.file.ImageUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.redis.utils.RedisUtils;
import com.ruoyi.gather.api.RemoteCollectProductCategoryService;
import com.ruoyi.gather.api.RemoteCollectProductSkuPropertyService;
import com.ruoyi.gather.api.RemoteProductBrandService;
import com.wwb.collect.config.WwbProperties;
import com.wwb.collect.domain.*;
import com.wwb.collect.domain.bo.ErpWwbCollectProductBo;
import com.wwb.collect.domain.enums.WwbApiUrlEnum;
import com.wwb.collect.domain.vo.ErpWwbCollectProductVo;
import com.wwb.collect.mapper.*;
import com.wwb.collect.request.ProductListRequest;
import com.wwb.collect.response.ProductDetailResponse;
import com.wwb.collect.response.ProductListResponse;
import com.wwb.collect.response.ProductSkuResponse;
import com.wwb.collect.service.IWwbCollectProductHandleService;
import com.wwb.collect.service.IWwbCollectProductService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 微唯宝供应链采集商品
 * @Author: j.zh
 * @Date: 2024/6/6
 * @Version: 4.0.0
**/
@RequiredArgsConstructor
@Service
public class WwbCollectProductHandleServiceImpl implements IWwbCollectProductHandleService {

    private static final Logger log = LoggerFactory.getLogger(WwbCollectProductHandleServiceImpl.class);

    private final RestTemplate restTemplate;

    @Resource
    WwbProperties wwbProperties;
    @Resource
    ErpWwbCollectProductMapper wwbCollectProductMapper;
    @Resource
    ErpWwbCollectProductExpandMapper wwbCollectProductExpandMapper;
    @Resource
    ErpWwbCollectProductSkuMapper wwbCollectProductSkuMapper;
    @Resource
    ErpCollectProductBMapper collectProductBMapper;
    @Resource
    ErpCollectProductExpandBMapper collectProductExpandBMapper;
    @Resource
    ErpCollectProductSkuBMapper collectProductSkuBMapper;
    @Resource
    ErpWwbCategoryInfoMapper wwbCategoryInfoMapper;
    @Resource
    ErpCollectProductDistributeLogMapper distributeLogMapper;
    @Resource
    RemoteCollectCommonService remoteCollectCommonService;
    @Resource
    RemoteCollectProductCategoryService remoteCollectProductCategoryService;
    @Resource
    RemoteCollectProductSkuPropertyService remoteCollectProductSkuPropertyService;
    @Resource
    RemoteProductBrandService remoteProductBrandService;

    /**
     * @Description: 获取产品列表及详细信息
     * @Author: j.zh
     * @Date: 2024/6/8
     * @param productListRequest
     * @return
     * @Version: 4.0.0
    **/
    @Override
    public String getProductList(ProductListRequest productListRequest) {
        Date startCollect = new Date();
        log.debug("========开始采集========" + startCollect);
        // 获得当前页
        Integer currentPage = Integer.parseInt(productListRequest.getPage());
        List<ProductListResponse> productListResponseList = new ArrayList<>();
        // 页数递增进行列表采集
        while (true){
            List<ProductListResponse> temp = new ArrayList<>();
            temp = getProductListResponseList(productListRequest);
            if (temp != null){
                log.debug("当前采集到第" + currentPage + "页，成功采集" + temp.size() + "条SPU");
                productListResponseList.addAll(temp);
                currentPage++;
                productListRequest.setPage(currentPage.toString());
            }else {
                // 未采集到商品，退出循环
                break;
            }
        }
        if(productListResponseList.size() == 0){
            log.debug("========本次未采集到SPU========");
            return "本次未采集到SPU";
        }
        log.debug("========本次成功采集" + productListResponseList.size() + "条SPU========");
        log.debug("========本次采集耗时：" + DateUtils.timeDistance(new Date(), startCollect));

        // 保存或更新缓存
        productListResponseList = saveOrUpdateIdCache(productListResponseList);
        if(productListResponseList == null || productListResponseList.size() == 0){
            return "本次采集的SPU均已存在，不执行入库操作。";
        }
//        // 更新所有SKU属性名和属性值 数量太大，用一个缓存一个
//        if(remoteCollectProductSkuPropertyService.getValueList().getCode() != 200){
//            log.error("更新所有SKU属性名和属性值错误，退出采集");
//            return "更新所有SKU属性名和属性值错误，退出采集";
//        }
        log.debug("========本次可执行入库" + productListResponseList.size() + "条SPU========");

        // 小批量、分批次执行入库操作
        Integer successAllCount = 0;
        int i = 0;
        Date startAllInsert = new Date();
        List<List<ProductListResponse>> insertList = ListUtils.splitList(productListResponseList, 30);
        for (List<ProductListResponse> tempList : insertList){
            Integer successCount = insertDB(tempList, productListRequest, startCollect);
            successAllCount += successCount;
            i++;
            log.debug("========本批次成功入库" + successCount + "个SPU========");
            log.debug("========本次剩余未采集" + (productListResponseList.size()-(i*30)) + "个SPU========");
        }

        log.debug("========结束入库========");
        log.debug("========本次成功入库" + successAllCount + "个SPU========");
        log.debug("========本次总入库耗时：" + DateUtils.timeDistance(new Date(), startAllInsert));
        log.debug("========本次总耗时：" + DateUtils.timeDistance(new Date(), startCollect));
        return "采集入库全部完成";
    }

    /**
     * @Description: 批处理后将微唯宝商品分发至上品库
     * @Author: j.zh
     * @Date: 2024/6/15
     * @return
     * @Version: 4.0.0
     **/
    @Override
    public String batchProcessingToDistribute(){
        List<ErpWwbCollectProduct> newCollectProductList = null;
        // 查询粗过滤的列表，且没有精细过滤的，即主表operate_type=1，expand表edit_status=0
        List<ErpWwbCollectProduct> collectProductList = wwbCollectProductMapper.selectGeneralFilteringList();

        // 总共处理条数
        Integer totalCount = collectProductList.size();
        // 已处理条数
        Integer alreadyCount = 0;

        // 一次性查询，小批量处理
        List<List<ErpWwbCollectProduct>> insertListTemp = ListUtils.splitList(collectProductList, 30);
        log.debug("========共预计批量处理 " + totalCount + "个SPU========");
        for (List<ErpWwbCollectProduct> insertList : insertListTemp){
            // 1、2、3步进行批处理
            newCollectProductList = batchProcessingWWbOriginalProduct(insertList);
            alreadyCount += newCollectProductList.size();
            log.debug("========本批次预计处理 " + newCollectProductList.size() + "个SPU========");
            if (newCollectProductList == null || newCollectProductList.size() == 0){
                // 无可迁移的数据
                continue ;
            }
            log.debug("========开始复制迁移并入库========");
            /** 4、将新列表符合条件的插入到可上架的采集表，并更新expand表edit_status=1 **/
            // 复制product主表
            List<ErpCollectProductB> productBList = new ArrayList<>();
            ErpCollectProductB productB = null;
            for (ErpWwbCollectProduct wwbCollectProduct : newCollectProductList){
                productB = new ErpCollectProductB();
                BeanUtils.copyProperties(wwbCollectProduct, productB);
                productBList.add(productB);
            }
            // 复制product扩展表
            List<Long> newCollectProductIdList = newCollectProductList.stream().map(e -> e.getId()).collect(Collectors.toList());
            List<ErpWwbCollectProductExpand> wwbExpandList = wwbCollectProductExpandMapper.selectList(new LambdaQueryWrapper<ErpWwbCollectProductExpand>()
                    .in(ErpWwbCollectProductExpand::getCollectProductId, newCollectProductIdList));
            List<ErpCollectProductExpandB> productExpandBList = new ArrayList<>();
            ErpCollectProductExpandB  productExpandB = null;
            for (ErpWwbCollectProductExpand wwbCollectProductExpand : wwbExpandList){
                productExpandB = new ErpCollectProductExpandB();
                BeanUtils.copyProperties(wwbCollectProductExpand, productExpandB);
                productExpandBList.add(productExpandB);
                // 更新编辑状态为已编辑
                wwbCollectProductExpand.setEditStatus(1);
            }
            // 复制product sku表
            List<ErpWwbCollectProductSku> wwbSkuList = wwbCollectProductSkuMapper.selectList(new LambdaQueryWrapper<ErpWwbCollectProductSku>()
                    .in(ErpWwbCollectProductSku::getCollectProductId, newCollectProductIdList));
            List<ErpCollectProductSkuB> productSkuBList = new ArrayList<>();
            ErpCollectProductSkuB  productSkuB = null;
            for (ErpWwbCollectProductSku wwbCollectProductSku : wwbSkuList){
                productSkuB = new ErpCollectProductSkuB();

                List<Map<String,Object>> tempMapList = (List<Map<String, Object>>) JSONArray.parse(wwbCollectProductSku.getSkuAttr());
                String skuName = "";
                for (Map<String, Object> tempMap : tempMapList){
                    if (!tempMap.get("val").toString().equals("无规格")){
                        skuName = skuName + tempMap.get("val").toString() + "+";
                    }
                }
                if (skuName != null && !skuName.trim().equals("")){
                    skuName = skuName.substring(0, skuName.length() -1 );
                }

                BeanUtils.copyProperties(wwbCollectProductSku, productSkuB);
                productSkuB.setSkuName(skuName);
                productSkuBList.add(productSkuB);
            }

            // 批量入库
            collectProductBMapper.insertBatch(productBList);
            collectProductExpandBMapper.insertBatch(productExpandBList);
            collectProductSkuBMapper.insertBatch(productSkuBList);
            // 批量更新编辑状态
            wwbCollectProductExpandMapper.updateBatchById(wwbExpandList);
            // 批量插入分发表
            List<ErpCollectProductDistributeLog> distributeLogList = new ArrayList<>();
            ErpCollectProductDistributeLog distributeLog = null;
            for (ErpCollectProductB product : productBList){
                distributeLog = new ErpCollectProductDistributeLog();
                distributeLog.setCollectProductId(product.getId());
                distributeLog.setSource("wwb");
                distributeLog.setDistributeAe("0");
                distributeLog.setCreateBy("1");
                distributeLog.setCreateTime(new Date());
                distributeLogList.add(distributeLog);
            }
            distributeLogMapper.insertBatch(distributeLogList);
            log.debug("========本批次已成功入库 " + productBList.size() + "个SPU，剩余" + (totalCount - alreadyCount) + "========");
        }


        return "完成批处理";
    }

    /**
     * @Description: 批处理微唯宝的原始数据
     * @Author: j.zh
     * @Date: 2024/6/17
     * @param batchProcessingList
     * @return
     * @Version: 4.0.0
    **/
    private List<ErpWwbCollectProduct> batchProcessingWWbOriginalProduct(List<ErpWwbCollectProduct> batchProcessingList){
        List<ErpWwbCollectProduct> newCollectProductList = new ArrayList<>();
        StringBuffer newUrls = new StringBuffer();
        for (ErpWwbCollectProduct collectProduct : batchProcessingList){
            try {
                /** 1、轮播图尺寸，是否大于800*800并且长宽一致 **/
                for (String url : collectProduct.getImageURLs().split(";")){
                    List<Integer> size = ImageMergeUtils.getImageWidthAndHeight(url);
                    if (size.get(0).intValue() == size.get(1).intValue() && size.get(0).intValue() >= 800){
                        newUrls.append(url).append(";");
                    }
                }
                if (newUrls != null && !newUrls.toString().equals("") && !newUrls.toString().equals(";")){
                    collectProduct.setImageURLs(newUrls.substring(0, newUrls.length()-1));
                }else {
                    // 没有符合要求的轮播图，则忽略该品
                    continue;
                }

                /** 2、对需要白底图和营销图的商品进行抠图 **/
                // 判断白底图前缀，如果是空或者不包含https://erp-aliexpress.oss的，需要重新做白底图和营销图
                if (collectProduct.getWhite() == null || collectProduct.getWhite().trim().equals("")){
                    continue;
                }
                if (collectProduct.getWhite().contains("https://erp-aliexpress.oss")){
                    // 说明图已做好，无需修改
                }else {
                    // 根据url做白底营销
                    R<Object> objectR = remoteCollectCommonService.generateWhite(collectProduct.getWhite().replaceAll("/","@@@"));
                    if (objectR.getCode() != 200){
                        continue;
                    }
                    collectProduct.setWhite(objectR.getData().toString());
                    // 营销图
                    objectR = remoteCollectCommonService.generateMarketing(collectProduct.getWhite().replaceAll("/","@@@"));
                    if (objectR.getCode() != 200){
                        continue;
                    }
                    collectProduct.setMarketing(objectR.getData().toString());
                }
                /** 3、对标题进行粗处理 无效词、【】、[]、2023、2022**/
                collectProduct.setSubject(collectProduct.getSubject().replaceAll("-无规格","").replaceAll("亏本","")
                        .replaceAll("清理库存","").replaceAll("库存","").replaceAll("老师推荐","")
                        .replaceAll("工厂直销","").replaceAll("工厂现货","").replaceAll("工厂","")
                        .replaceAll("厂家直销","").replaceAll("厂家现货","").replaceAll("厂家","")
                        .replaceAll("促销中","").replaceAll("促销","").replaceAll("不好用包赔","")
                        .replaceAll("手慢无","").replaceAll("一件代发","").replaceAll("小红书","")
                        .replaceAll("亏本清理库存", "").replaceAll("清理库存", "").replaceAll("亏本清理", "")
                        .replaceAll("库存", "").replaceAll("清理库存", "").replaceAll("亏本清理", "")
                        .replaceAll("抖音","").replaceAll("2023","2024").replaceAll("2022","2024"));
                collectProduct.setSubject(collectProduct.getSubject()
                        .replaceAll("【】","")
                        .replaceAll("\\[]",""));

                newCollectProductList.add(collectProduct);
            } catch (Exception e) {
                e.printStackTrace();
                log.debug("========错误商品ID：" + collectProduct.getId() + "========");
                log.debug("========错误商品Urls：" + collectProduct.getImageURLs() + "========");
                log.debug("========错误商品White：" + collectProduct.getWhite() + "========");
                log.debug("========错误商品Subject：" + collectProduct.getSubject() + "========");
                continue;
            }
        }

        return newCollectProductList;
    }

    /**
     * @Description: 保存或更新缓存
     * @Author: j.zh
     * @Date: 2024/6/13
     * @param productListResponseList
     * @return
     * @Version: 4.0.0
    **/
    private List<ProductListResponse> saveOrUpdateIdCache(List<ProductListResponse> productListResponseList){
        List<Integer> alreadyExistIdList = new ArrayList<>();
        // 1、先查询是否有缓存
        if (RedisUtils.isExistsObject("wwbCollectIdList")){
            // 有缓存，取出缓存
            alreadyExistIdList = RedisUtils.getCacheObject("wwbCollectIdList");
        }else {
            // 无缓存，查询数据库
            List<ErpWwbCollectProductExpand> tempProductExpandList = wwbCollectProductExpandMapper.selectList();
            if (tempProductExpandList.size() > 0){
                alreadyExistIdList = tempProductExpandList.stream()
                        .map(e -> e.getWwbProductId()).collect(Collectors.toList());
            }
        }
        // 2、判断已存在列表，如果无，则直接返回本次采集集合
        if(alreadyExistIdList == null || alreadyExistIdList.size() == 0){
            // 放入缓存
            RedisUtils.setCacheObject("wwbCollectIdList", productListResponseList.stream()
                    .map(e -> e.getGoods_id()).collect(Collectors.toList()));
            return productListResponseList;
        }
        // 3、存在缓存，则根据已存在的ID，进行去重操作
        List<ProductListResponse> resultList = new ArrayList<>();
        for (ProductListResponse temp : productListResponseList){
            if (!alreadyExistIdList.contains(temp.getGoods_id())){
                // 不存在，则准备继续采集后续操作，存在，则忽略
                resultList.add(temp);
            }
        }
        if (resultList == null || resultList.size() == 0){
            // 本次采集品均早已入库
            return null;
        }
        // 4、将本次采集ID集合和已存在的进行合并，并更新缓存
        alreadyExistIdList.addAll(resultList.stream()
                .map(e -> e.getGoods_id()).collect(Collectors.toList()));
        RedisUtils.setCacheObject("wwbCollectIdList", alreadyExistIdList);
        return resultList;
    }

    /**
     * @Description: 获取商品基本信息列表
     * @Author: j.zh
     * @Date: 2024/6/6
     * @param productListRequest
     * @return
     * @Version: 4.0.0
    **/
    private List<ProductListResponse> getProductListResponseList(ProductListRequest productListRequest){
        // 获取商品列表api
        String url = wwbProperties.getUrl() + "/api_" + wwbProperties.getVersion()
                + WwbApiUrlEnum.getGoodsList.getApi();

        ResponseEntity<String> forEntity = restTemplate.postForEntity(
                url, productListRequest, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);

        Integer errCode = jsonObject.getInteger("error_code");
        if (errCode == 0){
            // 获取结果集
            JSONObject result = jsonObject.getJSONObject("result");
            // 获取商品列表
            JSONArray jsonArray = result.getJSONArray("list");
            if (jsonArray.isEmpty()){
                return null;
            }
            return jsonArray.toJavaList(ProductListResponse.class);
        }else {
            log.error("获取商品列表失败!!当前采集为第"+productListRequest.getPage()+"页");
            log.error("errCode=" + errCode + ",errInfo=" + jsonObject.getString("error_msg"));
            return null;
        }
    }

    /**
     * @Description: 根据产品ID，获取产品详情
     * @Author: j.zh
     * @Date: 2024/6/7
     * @param productId
     * @return
     * @Version: 4.0.0
    **/
    private ProductDetailResponse getProductDetailResponse(String token, Integer productId){
        // 获取商品详情api
        String url = wwbProperties.getUrl() + "/api_" + wwbProperties.getVersion()
                + WwbApiUrlEnum.getGoodDetail.getApi();
        Map<String, String> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("goods_id", productId.toString());

        ResponseEntity<String> forEntity = restTemplate.postForEntity(
                url, requestParams, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);

        Integer errCode = jsonObject.getInteger("error_code");
        if (errCode == 0){
            // 获取结果集
            JSONObject result = jsonObject.getJSONObject("result");
            ProductDetailResponse response = JSONObject.parseObject(result.toString(), ProductDetailResponse.class);
            return response;
        }else {
            log.error("获取商品详情失败!!当前采集商品ID为：" + productId +"");
            log.error("errCode=" + errCode + ",errInfo=" + jsonObject.getString("error_msg"));
            return null;
        }
    }

    /**
     * @Description: 获取产品SKU详情
     * @Author: j.zh
     * @Date: 2024/6/7
     * @param token
     * @param skuId
     * @param skuSn
     * @return
     * @Version: 4.0.0
    **/
    private ProductSkuResponse getProductSkuResponse(String token, Integer skuId, String skuSn){
        // 获取商品详情api
        String url = wwbProperties.getUrl() + "/api_" + wwbProperties.getVersion()
                + WwbApiUrlEnum.getGoodSkuDetail.getApi();
        Map<String, String> requestParams = new HashMap<>();
        requestParams.put("access_token", token);
        requestParams.put("sku_id", skuId.toString());
        requestParams.put("sku_sn", skuSn);

        ResponseEntity<String> forEntity = restTemplate.postForEntity(
                url, requestParams, String.class);
        String body = forEntity.getBody();
        JSONObject jsonObject = JSONObject.parseObject(body);

        Integer errCode = jsonObject.getInteger("error_code");
        if (errCode == 0){
            // 获取结果集
            JSONObject result = jsonObject.getJSONObject("result");
            ProductSkuResponse response = JSONObject.parseObject(result.toString(), ProductSkuResponse.class);
            return response;
        }else {
            log.error("获取商品SKU失败!!当前采集商品SkuId：" + skuId +", SkuSn:" + skuSn);
            log.error("errCode=" + errCode + ",errInfo=" + jsonObject.getString("error_msg"));
            return null;
        }
    }

    /**
     * @Description: 将微唯宝采集商品按格式对应到标准采集表
     * @Author: j.zh
     * @Date: 2024/6/9
     * @param collectProductId
     * @param productDetail
     * @return
     * @Version: 4.0.0
    **/
    private ErpWwbCollectProduct combinationProduct(long collectProductId, Integer categoryId, ProductDetailResponse productDetail){
        ErpWwbCollectProduct wwbCollectProduct = new ErpWwbCollectProduct();
        wwbCollectProduct.setId(collectProductId);
        // 类目ID，根据微唯宝类目ID，查找对应ID
        wwbCollectProduct.setCategoryId(getCategoryIdByWwb(categoryId));

        // 商品主图轮播图，确认分隔符
        String carouselImg = replaceDetailUrl(productDetail.getSku_list().get(0).getCarousel_img());
        if (carouselImg.split(";").length < 6 && !carouselImg.contains(productDetail.getMain_img())){
            // 轮播图少于6张且不包含主图，则拼接成轮播图
            carouselImg = productDetail.getMain_img() + ";" + carouselImg;
        }
        wwbCollectProduct.setImageURLs(carouselImg);
        // 商品标题
        wwbCollectProduct.setSubject(productDetail.getSpu_name());
        // 白底图，用主图进行设置，粗过滤后进行抠图操作
//        R<Object> objectR = remoteCollectCommonService.generateWhite(productDetail.getMain_img().replaceAll("/","@@@"));
//        wwbCollectProduct.setWhite(objectR.getCode() == 200 ? objectR.getData().toString() : null);
        // 营销图，用主图进行设置，粗过滤后进行抠图操作
//        objectR = remoteCollectCommonService.generateMarketing(productDetail.getMain_img().replaceAll("/","@@@"));
//        wwbCollectProduct.setMarketing(objectR.getCode() == 200 ? objectR.getData().toString() : null);
        // 采集商品的成本价
        wwbCollectProduct.setCollectProductPrice(productDetail.getCost_price());
        // 商品重量，接口未提供，孙泽谏统一批处理

        // 商品单位，默认100000015（件/个）
        wwbCollectProduct.setProductUnit(100000015l);
        // 详情图，确认分隔符
        wwbCollectProduct.setDetailImg(replaceDetailUrl(productDetail.getDetail_img()));
        // 采集链接，默认值
        wwbCollectProduct.setCollectUrl("微唯宝供应链");
        // 采集人
        wwbCollectProduct.setCollectUserId(1l);
        // 常规属性
        wwbCollectProduct.setCreateBy("1");
        wwbCollectProduct.setCreateTime(new Date());
        wwbCollectProduct.setDelFlag("0");
        wwbCollectProduct.setOperateType(0);

        return wwbCollectProduct;
    }

    /**
     * @Description: 根据微唯宝类目ID，查询对应AE的类目ID
     * @Author: j.zh
     * @Date: 2024/6/9
     * @param categoryId
     * @return
     * @Version: 4.0.0
    **/
    private Long getCategoryIdByWwb(Integer categoryId) {
//        // 优先查缓存是否存在该类目
//        if(RedisUtils.isExistsObject("WWB_CATEGORY_" + categoryId)){
//            return RedisUtils.getCacheObject("WWB_CATEGORY_" + categoryId);
//        }

        // 1、查找对应ID
        ErpWwbCategoryInfo categoryInfo = wwbCategoryInfoMapper.selectOne(new LambdaQueryWrapper<ErpWwbCategoryInfo>()
                .eq(ErpWwbCategoryInfo::getId, categoryId));
        //如果是空，则说明没有记录该类目，无法匹配。如果是"-"开头，说明已经匹配过，但没有合适类目或匹配出多个类目，需要进行人工匹配
        if (categoryInfo == null ||
                (categoryInfo.getAeCategoryId() != null && categoryInfo.getAeCategoryId().startsWith("-"))){
            return null;
        }
        if (categoryInfo != null && categoryInfo.getAeCategoryId() != null
                && !categoryInfo.getAeCategoryId().startsWith("-")){
            String aeCateId = categoryInfo.getAeCategoryId().replaceAll("\\[","").replaceAll("]","").trim();
            if (aeCateId.contains(",") || aeCateId.split(",").length > 1){
                return null;
            }
            return Long.parseLong(aeCateId);
        }
        // 2、没有对应，则进行匹配
        R<Object> categoryR = remoteCollectProductCategoryService.getCategoryIdListByCategoryName(categoryInfo.getCname().replaceAll("/", "@@@"));
        if (categoryR.getCode() != 200){
            // AE无对应类目
            categoryInfo.setAeCategoryId("-");
            // 更新类目
            wwbCategoryInfoMapper.updateById(categoryInfo);
            return null;
        }else {
            List<Long> categoryIdList = JSONArray.parseArray(JSONObject.toJSONString(categoryR.getData()), Long.class);
            categoryInfo.setAeCategoryId(StringUtils.join(categoryIdList).replaceAll("\\[","").replaceAll("]","").trim());
            // 更新类目
            wwbCategoryInfoMapper.updateById(categoryInfo);
            if (categoryIdList!=null && categoryIdList.size()==1){
                return categoryIdList.get(0);
            }else {
                return null;
            }
        }



    }

    /**
     * @Description: 将微唯宝采集商品按格式对应到标准采集扩展表
     * @Author: j.zh
     * @Date: 2024/6/9
     * @param collectProductId
     * @param productDetail
     * @return
     * @Version: 4.0.0
    **/
    private ErpWwbCollectProductExpand combinationProductExpand(long collectProductId, Integer categoryId, ProductDetailResponse productDetail){
        ErpWwbCollectProductExpand productExpand = new ErpWwbCollectProductExpand();
        // 标准采集商品ID
        productExpand.setCollectProductId(collectProductId);
        // 微唯宝商品ID
        productExpand.setWwbProductId(productDetail.getGoods_id());
        // 微唯宝类目ID
        productExpand.setWwbCategoryId(categoryId);

        // SKU规则，基本格式为：[{"name": "颜色", "value": 21, "list": [{"name": "specifications", "value": 73069}]}]
        productExpand.setSkuProperty(combinationSkuFormat(productDetail.getSku_list()));
        // 商品品牌，接口返回品牌名称，需对应品牌ID
//        System.out.println("========" + productDetail.getBrand_name() + "=========");
        if (productDetail.getBrand_name() == null || productDetail.getBrand_name().trim().equals("")
                || productDetail.getBrand_name().equals("其他品牌")){

        }else {
            productExpand.setBrandId(Long.parseLong(getProductBrandByName(productDetail.getBrand_name())));
        }

        // 区域定价类型，默认自动
        productExpand.setAbsoluteQuoteType(1);
        // 是否计算运费
        productExpand.setIsFreight(0);
        // 是否自定义计重
        productExpand.setIsPackSell("0");
        // 默认备货期
        productExpand.setDeliveryTime(7l);
        //
        productExpand.setIsImageDynamic("0");
        // 是否打包销售
        productExpand.setPackageType("0");
        // 产品上架状态
        productExpand.setProductStatus(0);
        // 编辑状态
        productExpand.setEditStatus(0);
        // 优化状态
        productExpand.setIsOptimize(0);
        // 是否含非液体化妆品
        productExpand.setIsAneroidMarkup(0);
        // 是否含纯电池产品（必填，填0代表不含纯电池产品
        productExpand.setIsOnlyBattery(0);
        // 是否包含锂电池(必填0/1)
        productExpand.setIsContainsBattery(0);
        // 是否已经翻译（0否 1是）
        productExpand.setIsTranslate(0);
        // 是否已测试 0未测试发布
        productExpand.setIsUploadTest(0);
        // 是否自动优化
        productExpand.setIsAutoOptimize(0);
        // 是否含有品牌词：0未验证，1验证通过不含品牌词 2存在品牌词
        productExpand.setIsViola(0);
        // 商品编码
        productExpand.setSpuSn(productDetail.getSpu_sn());
        // 限购数量
        productExpand.setLimitNum(productDetail.getLimit_num());
        // 微唯宝商品状态（0=下架，1=上架，3=删除）
        productExpand.setStatus(productDetail.getStatus());
        // 商品建议零售价
        productExpand.setRetailPrice(new BigDecimal(productDetail.getRetail_price()));
        // 利润率，百分比
        productExpand.setProfit(productDetail.getProfit());
        // 顶图
        productExpand.setTopImg(productDetail.getTop_img());
        // 提示图片
        productExpand.setBottomImg(productDetail.getBottom_img());

        // 常规属性
        productExpand.setCreateBy("1");
        productExpand.setCreateTime(new Date());
        productExpand.setDelFlag("0");

        return productExpand;
    }

    /**
     * @Description: 将微唯宝采集商品按格式对应到标准采集SKU表
     * @Author: j.zh
     * @Date: 2024/6/9
     * @param collectProductId
     * @param skuDetail
     * @return
     * @Version: 4.0.0
     **/
    private ErpWwbCollectProductSku combinationProductSku(long collectProductId, ProductSkuResponse skuDetail){
        ErpWwbCollectProductSku productSku = new ErpWwbCollectProductSku();

        productSku.setCollectProductId(collectProductId);
        // 生成系统内skuCode
        productSku.setSkuCode(CommonUtils.getSkuCodeByPrefix("WB"));
        // SKU名称
        productSku.setSkuName(skuDetail.getSku_name());
        // SKU图片
        productSku.setSkuImage(skuDetail.getMain_img());
        // SKU成本价
        productSku.setCollectSkuPrice(skuDetail.getCost_price());
        // sku采购链接
        productSku.setSkuBuyLink("微唯宝供应链");
        // sku价格
        productSku.setSkuPrice(skuDetail.getCost_price());
        // sku属性ID集合;单组合，如"颜色：红色"存储"3:4"，多组合，如"颜色：红色；内存：256M"存储为"3:4;2:5"
        // [{"name":"规格","val":"LP-21873棉柔卷巾3卷装"},{"name":"件","val":"件"}]
//        System.out.println("========" + skuDetail.getAttr() + "========");
        StringBuffer skuIds = new StringBuffer();
        List<Map<String,Object>> tempMapList = (List<Map<String, Object>>) JSONArray.parse(skuDetail.getAttr());
        for (Map<String, Object> tempMap : tempMapList){
            String ids = getSkuPropertyOrValueId("P", replaceProperty(tempMap.get("name").toString())) + ":"
                    + getSkuPropertyOrValueId("PV", replaceProperty(tempMap.get("val").toString())) + ";";
            skuIds.append(ids);
        }

//        System.out.println("========" + skuIds.toString() + "========");
        productSku.setSkuPropertyIds(skuIds.toString().substring(0, skuIds.toString().length() - 1));
        // 微唯宝规格编码
        productSku.setSkuSn(skuDetail.getSku_sn());
        // 微唯宝规格起购数
        productSku.setLowestNum(skuDetail.getLowest_num());
        // 微唯宝规格状态0=下架，1=上架
        productSku.setStatus(skuDetail.getStatus());
        // 微唯宝规格建议零售价
        productSku.setRetailPrice(skuDetail.getRetail_price());
        // 微唯宝规格最低限价
        productSku.setFloorPrice(skuDetail.getFloor_price());
        // 微唯宝规格利润率
        productSku.setProfit(skuDetail.getProfit());
        // 微唯宝规格
        productSku.setSkuAttr(skuDetail.getAttr());
        // 常规属性
        productSku.setCreateBy("1");
        productSku.setCreateTime(new Date());
        productSku.setDelFlag("0");

        return productSku;
    }

    /**
     * @Description: 根据微唯宝提供的SKU格式，转化成标准采集格式
     * @Author: j.zh
     * @Date: 2024/6/12
     * @param skuList
     * @return
     * @Version: 4.0.0
     **/
    private String combinationSkuFormat(List<ProductSkuResponse> skuList) {
        // [{"name":"规格","val":"LP-21873棉柔卷巾3卷装"},{"name":"件","val":"件"}]
        // [{"name":"规格","val":"LP-21873棉柔卷巾10卷装"},{"name":"件","val":"件"}]
        // SKU规则，基本格式为：
        // [{"name": "规格", "value": 21, "list": [{"name": "LP-21873棉柔卷巾3卷装", "value": 73069},{"name": "LP-21873棉柔卷巾10卷装", "value": 73069}]},{"name": "件", "value": 21, "list": [{"name": "件", "value": 73069}]}]

        List<Map<String,Object>> allMap = new ArrayList<>();
        // 循环获取sku规格
        for (ProductSkuResponse skuResponse : skuList){
            List<Map<String,Object>> tempMap = (List<Map<String, Object>>) JSONArray.parse(skuResponse.getAttr());
            allMap.addAll(tempMap);
        }

        // 将规格和规格值进行分类
        Map<String, String> newPropertyMap = new HashMap<>();
        for (Map<String, Object> propertyMap : allMap){
            if (newPropertyMap.containsKey(replaceProperty(propertyMap.get("name").toString()))){
                newPropertyMap.put(replaceProperty(propertyMap.get("name").toString()),
                        newPropertyMap.get(replaceProperty(propertyMap.get("name").toString()))
                                + "," + replaceProperty(propertyMap.get("val").toString()));
            }else {
                newPropertyMap.put(replaceProperty(propertyMap.get("name").toString()),
                        replaceProperty(propertyMap.get("val").toString()));
            }
        }

        List<SkuPropertyDto> propertyList = new ArrayList<>();
        SkuPropertyDto property = null;
        for (String newKey : newPropertyMap.keySet()){
            property = new SkuPropertyDto();
            // 获取规格键值对
            property.setValue(getSkuPropertyOrValueId("P", newKey));
            property.setName(newKey);
            List<SkuPropertyDto> propertyValueList = new ArrayList<>();
            SkuPropertyDto propertyValue = null;
            for (String value : newPropertyMap.get(newKey).split(",")){
//                System.out.println("==========" + value + "==========");
                propertyValue = new SkuPropertyDto();
                propertyValue.setValue(getSkuPropertyOrValueId("PV", value));
                propertyValue.setName(value);
                propertyValueList.add(propertyValue);
            }
            property.setList(propertyValueList);
            propertyList.add(property);
//            System.out.println("==========" + JSON.toJSONString(propertyList) + "==========");
//            System.out.println("==============================");
        }
        // 将实体类转为JSON字符串
        return JSON.toJSONString(propertyList);
    }

    /**
     * @Description: 执行入库操作
     * @Author: j.zh
     * @Date: 2024/6/13
     * @param productListResponseList
     * @param productListRequest
     * @param startCollect
     * @return
     * @Version: 4.0.0
    **/
    private Integer insertDB(List<ProductListResponse> productListResponseList, ProductListRequest productListRequest, Date startCollect){
        // 临时保存，批量插入
        List<ErpWwbCollectProduct> wwbCollectProductList = new ArrayList<>();
        List<ErpWwbCollectProductSku> wwbCollectProductSkuList = new ArrayList<>();
        List<ErpWwbCollectProductExpand> wwbCollectProductExpandList = new ArrayList<>();

        // 获取标准采集表的当前最大ID
        Long maxCollectProductId = wwbCollectProductMapper.selectMaxId();
        if (maxCollectProductId == null){
            maxCollectProductId = 1790633957624619068l;
        }
        // 本次最终入库的准确个数
        int spuCount = 0;
        // 出错的SPU_ID
        Integer errorGoodId = 0;
        // 出错的SPU_ID缓存集合
        List<Integer> errorList = new ArrayList<>();
        if (RedisUtils.isExistsObject("wwbCollectErrorList")){
            errorList = RedisUtils.getCacheObject("wwbCollectErrorList");
        }
        ErpWwbCollectProduct errorCollectProduct = null;
        ErpWwbCollectProductSku errorCollectProductSku = null;
        ErpWwbCollectProductExpand errorCollectProductExpand = null;
        // 根据产品列表信息，采集产品详情和SKU详情
        for (ProductListResponse productListResponse : productListResponseList){
            try {
                errorGoodId = productListResponse.getGoods_id();
                // 判断是否之前采集出错，需要跳过
                if (errorList != null && errorList.size() > 0 && errorList.contains(errorGoodId)){
                    // 跳过
                    continue;
                }
                log.debug("========正在执行商品采集，SPU_SN：" + productListResponse.getSpu_sn() + "========");
                // 遍历列表，查询详情
                ProductDetailResponse productDetailResponse =
                        getProductDetailResponse(productListRequest.getAccess_token(), productListResponse.getGoods_id());
                if (productDetailResponse == null || productDetailResponse.getStatus() != 1){
                    // 无详情或已下架
                    continue;
                }

                // 标准采集表的主键自增
                maxCollectProductId++;

                // ******组合商品详情数据
                errorCollectProduct = combinationProduct(maxCollectProductId, productListResponse.getCate_id(), productDetailResponse);
                wwbCollectProductList.add(errorCollectProduct);
                // ******组合商品扩展表数据
                errorCollectProductExpand = combinationProductExpand(maxCollectProductId, productListResponse.getCate_id(), productDetailResponse);
                wwbCollectProductExpandList.add(errorCollectProductExpand);

                // 根据产品详情的skuList，获取产品SKU详情
                List<ProductSkuResponse> productSkuResponses = productDetailResponse.getSku_list();
                for (ProductSkuResponse skuDetail : productSkuResponses){
                    log.debug("========正在执行商品SKU采集，SKU_SN：" + skuDetail.getSku_sn() + "========");
                    skuDetail = getProductSkuResponse(productListRequest.getAccess_token(),
                            skuDetail.getSku_id(), skuDetail.getSku_sn());
                    if (skuDetail == null || skuDetail.getStatus() != 1){
                        // 无详情或已下架
                        continue;
                    }
                    // ******组合商品SKU详情数据
                    errorCollectProductSku = combinationProductSku(maxCollectProductId, skuDetail);
                    wwbCollectProductSkuList.add(errorCollectProductSku);
                }
                spuCount++;
                log.debug("========采集完成" + spuCount + "条SPU========");
            } catch (Exception e) {
                // 将采集错误商品放入缓存，下次直接跳过
                if (RedisUtils.isExistsObject("wwbCollectErrorList")){
                    errorList = RedisUtils.getCacheObject("wwbCollectErrorList");
                    errorList.add(errorGoodId);
                    RedisUtils.setCacheObject("wwbCollectErrorList", errorList);
                }else {
                    errorList.add(errorGoodId);
                    RedisUtils.setCacheObject("wwbCollectErrorList", errorList);
                }
                log.error("采集出错 {}", e);
                log.debug("========采集出错，开始执行补救措施========");
                // 执行过程中出错，将未执行的商品从入库列表中移除
                wwbCollectProductList.remove(errorCollectProduct);
                wwbCollectProductExpandList.remove(errorCollectProductExpand);
                wwbCollectProductSkuList.remove(errorCollectProductSku);

                // 从已采集ID列表中移除
                boolean isRemove = false;
                List<Integer> alreadyExistIdList = RedisUtils.getCacheObject("wwbCollectIdList");
                // 从缓存中移除
                alreadyExistIdList.remove(productListResponse.getGoods_id());
                RedisUtils.setCacheObject("wwbCollectIdList", alreadyExistIdList);
                // 将已采集完的数据入库
            }
        }

        if (wwbCollectProductList == null || wwbCollectProductList.size() == 0){
            return spuCount;
        }
        Date startInsert = new Date();
        log.debug("========开始入库========" + startInsert);
        // 批量入库
        wwbCollectProductMapper.insertBatch(wwbCollectProductList);
        wwbCollectProductExpandMapper.insertBatch(wwbCollectProductExpandList);
        wwbCollectProductSkuMapper.insertBatch(wwbCollectProductSkuList);
        log.debug("========成功入产品库" + spuCount + "条SPU========");
        log.debug("========成功入产品扩展库" + spuCount + "条SPU========");
        log.debug("========成功入产品SKU库" + wwbCollectProductSkuList.size() + "条SKU========");
        log.debug("========本次入库耗时：" + DateUtils.timeDistance(new Date(), startInsert));
        return spuCount;
    }

    /**
     * @Description: 根据类型和名称，获取属性值或属性名的ID
     * @Author: j.zh
     * @Date: 2024/6/14
     * @param type
     * @param name
     * @return
     * @Version: 4.0.0
    **/
    private String getSkuPropertyOrValueId(String type, String name){
        // 优先查缓存
        if (RedisUtils.isExistsObject(type + "_" + name)){
            return RedisUtils.getCacheObject(type + "_" + name);
        }

        // 无缓存，先入库后加缓存
        String id = remoteCollectProductSkuPropertyService.getValueById(type, name);
        RedisUtils.setCacheObject(type + "_" + name, id);
        return id;
    }

    /**
     * @Description: 根据品牌名，获取品牌ID
     * @Author: j.zh
     * @Date: 2024/6/14
     * @param brandName
     * @return
     * @Version: 4.0.0
    **/
    private String getProductBrandByName(String brandName){
        if (RedisUtils.isExistsObject("brandName_" + brandName)){
            return RedisUtils.getCacheObject("brandName_" + brandName);
        }
        String brandId = remoteProductBrandService.getBrandByName(brandName);
        RedisUtils.setCacheObject("brandName_" + brandName, brandId);
        return brandId;
    }

    /**
     * @Description: 替换特殊字符
     * @Author: j.zh
     * @Date: 2024/6/12
     * @return
     * @Version: 4.0.0
    **/
    private String replaceProperty(String value){
        if (value == null || value.trim().equals("")){
            return "规格";
        }
        return value.replaceAll("【","[").replaceAll("】","]")
                .replaceAll("/","+").replaceAll("\\\\","+");
    }
    private String replaceDetailUrl(String value){
        return value.replaceAll("\\[","").replaceAll("]","")
                .replaceAll("\"","").replaceAll(",",";").replaceAll("，",";");
    }


    // 临时方法，处理完后合并至batchProcessingToDistribute()
    public String tempHandleSkuName(){
//        List<ErpWwbCollectProductSku> wwbCollectProductSkuList = wwbCollectProductSkuMapper.selectList();
//        List<ErpCollectProductSkuB> skuBList = new ArrayList<>();
//        ErpCollectProductSkuB skuB = null;
//        for (ErpWwbCollectProductSku wwbSku : wwbCollectProductSkuList){
//            skuB = new ErpCollectProductSkuB();
//            List<Map<String,Object>> tempMapList = (List<Map<String, Object>>) JSONArray.parse(wwbSku.getSkuAttr());
//            String skuName = "";
//            for (Map<String, Object> tempMap : tempMapList){
//                // [{"val":"【红色】2盒","name":"颜色"},{"val":"1","name":"规格"}]
//                // [{"val":"经典怀旧款：【益智游戏】木质挑挑棒","name":"款式"},{"val":"1-2人可玩：【1盒装】约31根","name":"套餐"}]
//                if (!tempMap.get("val").toString().equals("无规格")){
//                    skuName = skuName + tempMap.get("val").toString() + "+";
//                }
//            }
//            if (skuName != null && !skuName.trim().equals("")){
//                skuName = skuName.substring(0, skuName.length() -1 );
//            }
//            BeanUtils.copyProperties(wwbSku, skuB);
//            skuB.setSkuName(skuName);
//            skuBList.add(skuB);
//        }
//
//        collectProductSkuBMapper.updateBatchById(skuBList);
        return "";
    }

    public static void main(String args[]){
//        String attr = "[{\"name\":\"规格\",\"val\":\"LP-21873棉柔卷巾3卷装\"},{\"name\":\"件\",\"val\":\"件\"}]";
//        List<Map<String,String>> objectFir = (List<Map<String, String>>) JSONArray.parse(attr);
//        String attr2 = "[{\"name\":\"规格\",\"val\":\"LP-21873棉柔卷巾3卷装\"},{\"name\":\"件\",\"val\":\"件\"}]";
//        List<Map<String,String>> objectFir2 = (List<Map<String, String>>) JSONArray.parse(attr2);
//        objectFir.addAll(objectFir2);
//        System.out.println("111");

//        String url = "http://images1.douhuomall.com/40baa13567d4ddd540fb62a01de25b836d015490.jpg?XJ2zdsLP3vnkC8_YDAaSVA&YJ6UFf_7ecGhEs5jU4J5SQ";
//        System.out.println(url);
//        String newUrl = url.replaceAll("/","@@@");
//        System.out.println(url.replaceAll("/","@@@"));
//        System.out.println(newUrl);
//        newUrl = url.replaceAll("@@@","/");
//        System.out.println(newUrl);
//        List<Integer> list = new ArrayList<>();
//        list.add(1);
//        list.add(2);
//        list.add(3);
//        list.add(4);
//        list.add(5);
//        list.add(6);
//        list.add(7);
//        list.add(8);
//        List<List<Integer>> lists = ListUtils.splitList(list, 3);
//        System.out.println("===========");


    }

}
